package game.tictactoe.impl;

import game.tictactoe.pojo.Board;
import game.tictactoe.pojo.Player;
import game.tictactoe.pojo.Seed;
import game.tictactoe.util.Utils;

public class GameInterfaceImpl implements GameInterface
{
	private static GameInterfaceImpl gameInterfaceImpl = new GameInterfaceImpl();
	private static Board board;
	private Player humanPlayer;
	private Player aiPlayer;

	private GameInterfaceImpl()
	{
	}

	public static GameInterface getGameInterfaceImpl()
	{
		return gameInterfaceImpl;
	}

	public int getGameStatus()
	{
		int gameStatus = -2;
		if (humanPlayer.hasPlayerWon(humanPlayer.getMySeed(), board))
		{
			gameStatus = humanPlayer.getMySeed().getGameValue();
		}
		else
		{
			if (aiPlayer.hasPlayerWon(aiPlayer.getMySeed(), board))
			{
				gameStatus = aiPlayer.getMySeed().getGameValue();
			}
			else
			{
				if (board.isBoardFull())
				{
					gameStatus = 0;
				}
			}
		}
		return gameStatus;
	}

	public void setBoard(int rowIndex, int colIndex)
	{
		board = new Board(rowIndex, colIndex);
	}

	public Board getBoard()
	{
		return board;
	}

	public boolean processMove(int userMove, Seed seed)
	{
		int rowIndex = -1, colIndex = -1;
		String userInput = Utils.getArrayIndexFromString(userMove);

		if (userInput == null || userInput.isEmpty())
		{
			return false;
		}

		String[] splitStringArray = userInput.split(",");
		if (splitStringArray.length == 2)
		{
			rowIndex = Integer.parseInt(splitStringArray[0]);
			colIndex = Integer.parseInt(splitStringArray[1]);
		}

		if (rowIndex != -1 && colIndex != -1)
		{
			boolean boardMoveSuccess = board.isMoveValid(rowIndex, colIndex, seed);
			if (boardMoveSuccess)
				return true;
		}
		return false;
	}

	public void setUpPlayers(Player humanPlayer, Player aiPlayer)
	{
		this.humanPlayer = humanPlayer;
		this.aiPlayer = aiPlayer;
	}

}
